//
// Created by 86176 on 2021/11/3.
//
#include "FilterChain.h"
#include "iostream"
#include "TailFilterChain.h"
#include "HeadFilterChain.h"

void FilterChain::messageRecevide(FilterChain *filterChain, Session *session, Message *message) {
    //    std::cout<<"here3";
    if(false != getMessage(session, session->getIoBuffer(), message))
        callNextMessageRecevide(session, message);
}

void FilterChain::callNextMessageRecevide(Session* session,Message *message) {
    //std::cout<<"callNextMessageRecevide:"<<std::endl;
    //std::cout<<session->ioBuffer->byteStream;
    //这个后面是链尾巴，准备调用IOhander
    if(linkToTail) {
        //连接到链条尾
//        std::cout<<"link"<<std::endl;
        TailFilterChain *tailFilterChain = (TailFilterChain *)nextChain;
        tailFilterChain->PostMessageToIOHander(session,message);
    }else{
        //链接非链尾
        FilterChain * nextfilterchain = nextChain;
        nextfilterchain->messageRecevide(nextfilterchain,session,message);
    }
}

FilterChain::FilterChain(const std::string& str) {
    this->lastChain = nullptr;
    this->nextChain = nullptr;
    this->chainName = str;
    this->linkToTail = false;
    std::cout<<"chainName:"<<str<<std::endl;
}

void FilterChain::messagePostvide(FilterChain *filterChain, Session *session, Message *message) {
    if(false != postMessage(session, session->getIoBuffer(), message)){
        callLastMessagePostvide(session, message);
    }
}

void FilterChain::callLastMessagePostvide(Session *session, Message *message) {
    //todo callLastMessageSentvide，过滤链FilterChain的api
    if(linkToHead) {
        //连接到链条头
        //std::cout<<"link"<<std::endl;
        HeadFilterChain *headFilterChain = (HeadFilterChain *)nextChain;
        headFilterChain->PostioBuffterToIocp(session,message);
    }else{
        //链接非链头
        FilterChain * nextfilterchain = nextChain;
        nextfilterchain->messagePostvide(nextfilterchain,session,message);
    }
}
